package com.sh4.util.wechatUtils;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

import com.sh4.util.HttpUtil;

import net.sf.json.JSONObject;

/**
 * 微信 服务 号
 * Created by huxiaohang on 2017/7/6.
 */
public class Core {


    /**
     * 验证签名
     *
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static boolean checkSignature(String signature, String timestamp, String nonce,String token) {
        String[] arr = new String[] { token, timestamp, nonce };
        // 将token、timestamp、nonce三个参数进行字典序排序
        Arrays.sort(arr);
        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            // 将三个参数字符串拼接成一个字符串进行sha1加密
            byte[] digest = md.digest(content.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        content = null;
        // 将sha1加密后的字符串可与signature对比，标识该请求来源于微信
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }

    /**
     * 将字节数组转换为十六进制字符串
     *
     * @param byteArray
     * @return
     */
    private static String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest += byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    /**
     * 将字节转换为十六进制字符串
     *
     * @param mByte
     * @return
     */
    private static String byteToHexStr(byte mByte) {
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        char[] tempArr = new char[2];
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
        tempArr[1] = Digit[mByte & 0X0F];

        String s = new String(tempArr);
        return s;
    }

    /**
     * 获取 服务号 access_token
     *
     * @return
     * @throws Exception
     */
    public static JSONObject getServeAccessToken(String AppID,String AppSecret) {
        String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppID
                + "&secret=" + AppSecret;
//        String accessToken = null;
        JSONObject json = null;
        try {
            json = JSONObject.fromObject(HttpUtil.doGet(getTokenUrl));
//            accessToken = json.getString("access_token");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        
        return json;
    }
    /**
     * 刷新access_token { "access_token":"ACCESS_TOKEN", "expires_in":7200,
     * "refresh_token":"REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE" }
     */
    public static JSONObject refresh_token(String refresh_token,String AppID)  {
        JSONObject json = null;
        try {
            String reUrl = "https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=" + AppID + "&grant_type=refresh_token"
                    + "&refresh_token=" + refresh_token;
            json = JSONObject.fromObject(HttpUtil.doGet(reUrl));

        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 获取公众号的自动回复规则
     *
     * @param accessToken
     * @return
     * @throws Exception
     */
    public String getResponseSpecification(String accessToken){
        String SMUrl = "https://api.weixin.qq.com/cgi-bin/get_current_autoreply_info?access_token="
                + accessToken;
        String result = null;
        try{
            result = HttpUtil.doGet(SMUrl);
        }catch (Exception e){

        }
        return result;
    }
    /**
     * 获取 微信服务IP地址
     *
     * @return
     * @throws Exception
     */
    public static JSONObject get_IP(String accessToken) {
        String IPurl = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token="+accessToken;
        JSONObject json = null;
        try {
            json = JSONObject.fromObject(HttpUtil.doGet(IPurl));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 获取 永久 素材
     *
     * @param type
     *            素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
     * @param offset
     *            从全部素材的该偏移位置开始返回，0表示从第一个素材 返回
     * @param count
     *            返回素材的数量，取值在1到20之间
     * @return
     * @throws Exception
     */
    public static String get_material(String type, String offset, String count,String accessToken) throws Exception {
        String url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token="
                + accessToken;
        String json = "{\"type\":\"" + type + "\",\"offset\":" + offset + ",\"count\":" + count + "}";
        return HttpUtil.doPost(json, url);
    }

    /**
     * 根据Code 换取登录人accessToken：
     */
    public static JSONObject getOauthAccessToken(String code,String AppID,String AppSecret){
        JSONObject json = null;
        try {
            String IPurl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + AppID + "&secret=" + AppSecret
                    + "&code=" + code + "&grant_type=authorization_code";
            json = JSONObject.fromObject(HttpUtil.doGet(IPurl));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    /**
     * 验证登录人 token 是否有效
     */
    public static boolean checkToken(String assessToken, String openId){
        String checkTokenUrl = null;
        JSONObject json = null;
        try {
            checkTokenUrl = "https://api.weixin.qq.com/sns/auth?access_token=" + assessToken + "&openid=" + openId;
            json = JSONObject.fromObject(HttpUtil.doGet(checkTokenUrl));
        }catch (Exception e){
            e.printStackTrace();
        }
        return "0" == json.get("errcode") ? true : false;
    }
    
    /**
     * 获取所有用 一次拉取调用最多拉取10000个关注者的OpenID，可以通过多次拉取的方式来满足需求。 第一个拉取的OPENID，不填默认从头开始拉取
     */
    public static JSONObject getUserList(String assessToken, String openId){
        String url = null;
        JSONObject json = null;
        try {
        	url = "https://api.weixin.qq.com/cgi-bin/user/get?access_token=" + assessToken + "&next_openid=" + openId;
            json = JSONObject.fromObject(HttpUtil.doGet(url));
        }catch (Exception e){
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 获取用户基本信息
     *
     * @param zh_CN
     *            语言
     * @return
     * @throws Exception
     */
    public static JSONObject getUserInfo(String openId, String zh_CN,String accessToken) {
        JSONObject result = null;
        try{
            String infoUrl = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken
                    + "&openid=" + openId + "&lang=" + zh_CN;
            result = JSONObject.fromObject(HttpUtil.doGet(infoUrl));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /**
     * 将一条长链接转成短链接 主要使用场景： 开发者用于生成二维码的原链接（商品、支付二维码等）太长导致扫码速度和成功率下降
     * ，将原长链接通过此接口转成短链接再生成二维码将大大提升扫码速度和成功率
     */
    public static String getShortUrl(String url,String accessToken) {
        String url1 = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=" +accessToken;
        String json = "{\"action\":\"long2short\",\"long_url\":\"" + url + "\"}";
        String rs = null;
        try {
            rs = JSONObject.fromObject(HttpUtil.doPost(json, url1)).getString("short_url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }
    

    /**
     *更新服务号菜单
     */
    public static String updateMenu(String menus,String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" +accessToken;
        String rs = null;
        try {
            rs = JSONObject.fromObject(HttpUtil.doPost(menus, url)).getString("errmsg");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return rs;
    }


    /**
     *   临时二维码
     *
     * @param Parameter    二维码参数
     * @param activeTime   604800 (最大7天)
     * @return
     * @throws Exception
     */

    public static String getInterimQRCode(String Parameter, String activeTime,String accessToken)  {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" +accessToken;
        String json = "{\"expire_seconds\": " + activeTime + ", \"action_name\": \"QR_SCENE\",\"action_info\": {\"scene\": {\"scene_id\":" + Parameter + "}}}";
        String QRCodeUrl = null;
        try {
            JSONObject	rs = JSONObject.fromObject(HttpUtil.doPost(json, url));
            QRCodeUrl = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket="+rs.getString("ticket");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return QRCodeUrl;
    }

    /**
     * 永久二维码 4294967295 临时二维码最大值 scene(1 0755 01 01)
     *
     * @param Parameter
     *            二维码参数
     * @param Type
     *            1 整数 2 字符串
     * @return ticket 获取的二维码ticket，凭借此ticket可以在有效时间内换取二维码
     * @throws Exception
     */

    public static String getForeverQRCode(String Parameter, int Type,String accessToken) {
        String url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
        String json = null;
        switch (Type){
            case 1:  // scene_id 1--100000
                json = "{\"action_name\": \"QR_LIMIT_SCENE\",\"action_info\": {\"scene\": { \"scene_id\":" + Parameter
                        + "}}}";
                return json;
            case 2:  // 字符串类型，长度限制为1到64
                json = "{\"action_name\":\"QR_LIMIT_STR_SCENE\",\"action_info\": { \"scene\": {\"scene_str\":\"" + Parameter
                        + "\"}}}";
                return json;
        }
        String QrCode = null;
        try {
            JSONObject rs = JSONObject.fromObject(HttpUtil.doPost(json, url));
            QrCode = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + rs.getString("ticket");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return QrCode;
    }
}

